<?php
namespace daswork\lib;

use daswork\lib\Config;

class Route
{
    public $model; # 模块
    public $ctrl; # 控制器
    public $action; #方法
    public function __construct()
    {
        //xx.com/index.php/index/index
        //xx.com/index/index
        /**
         * 1.隐藏index.php文件，引入.htaccess文件，与入口文件同级
         * 2.获取URL 参数部分，即get传值
         * 3.返回对应模块,控制器和方法 REQUEST_URI
         */
        $route = Config::get('route');

        if (isset($_SERVER['PATH_INFO'])&& $_SERVER['PATH_INFO'] != '/') {
            $path = $_SERVER['PATH_INFO'];
            $pathArr = explode('/', trim($path, '/'));//数组
            // echo json_encode($pathArr);
            // exit;
            if (isset($pathArr[0]) && !empty($pathArr[0])) {
                $this->model = $pathArr[0];
                unset($pathArr[0]);
            } else {
                $this->model = $route['m'];
            }
            if (isset($pathArr[1])) {
                $this->ctrl = ucfirst(camelize($pathArr[1]));
                unset($pathArr[1]);
            } else {
                $this->ctrl = $route['c'];
            }
            if (isset($pathArr[2])) {
                $this->action = camelize($pathArr[2]);
                unset($pathArr[2]);
            } else {
                $this->action = $route['a'];
            }

            //url 多余部分转换成GET eg:index/index/index/id/1 实现get传值
            // var_dump($pathArr);
            $count = count($pathArr) + 3;
            $i = 3;
            while ($i < $count) {
                if (isset($pathArr[$i+1])) {
                    $_GET[$pathArr[$i]] = $pathArr[$i+1];
                }
                $i = $i + 2;
            };
        } else {
            $this->model = $route['m'];
            $this->ctrl = $route['c'];
            $this->action = $route['a'];
        }

        $GLOBALS['model'] = $this->model;
        $GLOBALS['ctrl'] = $this->ctrl;
        $GLOBALS['action'] = $this->action;
    }
}
